package sxt.servlet;

import com.google.gson.Gson;
import dao.GoodsDao;
import sxt.service.GoodsService;
import sxt.service.impl.GoodsServiceImpl;
import vo.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/sxt/GoodsServlet")
public class GoodsServlet extends BaseServlet {

    GoodsService goodsService = new GoodsServiceImpl();

    //销售排行功能
    private void findAllGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.从页面获取数据--此步不需要,跳过

        //2.处理数据&直接进行数据的查找
        List<Goods> allGoods = goodsService.findAllGoods();

        //3.将结果返回给界面
        String json = new Gson().toJson(allGoods);

        resp.getWriter().write(json);

    }

    //最新菜品功能
    private void NewItemGoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.从客户端获取参数

        //2.处理参数
        List<Goods> newItemGoods = goodsService.findnewItemGoods();

        //3.把处理结果响应给客户端的浏览器
        req.setAttribute("newItemGoods", newItemGoods);
        req.getRequestDispatcher("/main.jsp").forward(req, resp);
    }

    //查看单个菜品，跳转到留言界面
    private void findOneGoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String type = req.getParameter("type");
//        System.out.println(type);

        //
        Goods oneGoods = goodsService.findOneGoods(id);
        //System.out.println(oneGoods.getImage());这一步出现了乱码，为什么

        //
        req.getSession().setAttribute("oneGoods", oneGoods);
        if ("admin".equals(type)) {//除了数字比较一律用equals
//            System.out.println(1);
            resp.sendRedirect(req.getContextPath() + "/goodsDetailsAdmin.jsp");
        } else {
//            System.out.println(2);
            resp.sendRedirect("/goodsDetails.jsp");
        }
    }

    /*删除菜品*/
    private void deleteGood(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));

        GoodsDao goodsDao = new GoodsDao();

        try {
            goodsDao.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        resp.sendRedirect("/ShowAllGoods?type=admin");
    }

}
